package io.github.mymonstercat.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@RequiredArgsConstructor
public class GetJsonData {

    private final ResourceLoader resourceLoader;

    @SneakyThrows
    public <T> List<T> getTestData(String fileName, Class<T> type) {
        // 获取资源
        Resource resource = resourceLoader.getResource("classpath:data/" + fileName);

        // 使用InputStream读取资源文件
        try (InputStream inputStream = resource.getInputStream()) {
            String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            return JSON.parseArray(content, type);
        }
    }

    @SneakyThrows
    public <T> List<T> getTestData(String fileName) {
        Resource resource = resourceLoader.getResource("classpath:data/" + fileName);
        File file = resource.getFile();
        String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);

        return JSON.parseObject(content, new TypeReference<List<T>>() {});
    }
}
